package com.lujianfei.waterpower;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.lujianfei.waterpower.base.BaseActivity;
import com.lujianfei.waterpower.base.CommonAdapter;
import com.lujianfei.waterpower.base.ViewHolder;
import com.lujianfei.waterpower.ui.main.MainContract;
import com.lujianfei.waterpower.ui.main.MainEntity;
import com.lujianfei.waterpower.ui.main.MainPresenter;
import com.lujianfei.waterpower.ui.settings.SetttingActivity;
import com.lujianfei.waterpower.utils.ResUtils;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements MainContract.View{

    MainContract.Presenter presenter;
    ListView listview;
    BaseAdapter adapter;
    List<MainEntity> mainEntities = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitleLeftImage(R.drawable.ic_setting);
        setTitleMiddleText(ResUtils.getString(R.string.app_name),true);
        presenter = new MainPresenter(this);
        initView();
        initEvent();
    }

    @Override
    public void onTitleLeftImageClick() {
        startActivity(new Intent(this,SetttingActivity.class));
    }

    private void initEvent() {
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:{
                        presenter.openPower();
                    }
                    break;
                    case 1:{
                        presenter.openWater();
                    }
                    break;
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        presenter.loadData();
    }

    private void initView() {
        listview = findViewById(R.id.listview);
    }

    @Override
    protected int getTitleBarResId() {
        return R.id.custom_titlebar;
    }

    @Override
    public void updateData(List<MainEntity> mainEntities) {
        if (null == adapter){
            adapter = new CommonAdapter<MainEntity>(this,this.mainEntities,R.layout.adapter_main_item) {
                @Override
                public void convert(ViewHolder viewHolder, MainEntity data) {
                    viewHolder.setText(R.id.txt_title,data.getTitle());
                }
            };
            listview.setAdapter(adapter);
        }
        this.mainEntities.clear();
        this.mainEntities.addAll(mainEntities);
        adapter.notifyDataSetChanged();
    }

    @Override
    public Context getContext() {
        return this;
    }
}
